package com.yj.agent.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yj.agent.bean.LoginModel;
import com.yj.agent.util.AESUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户管理后台登录拦截器
 */

@Component
public class AuthInterceptor implements HandlerInterceptor {

    final String key = "izUxyta7f7jHqmS9";
    //定义拦截规则

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

        try {
            LoginModel loginModel;
            String session = request.getParameter("session");
            if(StringUtils.isBlank(session)&&request.getSession().getAttribute("LOGIN_USER")==null){
                response.sendRedirect("/common/error");
                return false;
            }
            if(StringUtils.isNotBlank(session)){
                session = new String(AESUtils.decrypt(session, key, key));
                JSONObject jsonObject = JSON.parseObject(session);
                if(StringUtils.isBlank(jsonObject.getString("gamerId"))
                        ||StringUtils.isBlank(jsonObject.getString("isMgr"))){
                    response.sendRedirect("/common/error");
                    return false;
                }
                loginModel = new LoginModel();
                loginModel.setGamerId(jsonObject.getString("gamerId"));
                loginModel.setIsMgr(jsonObject.getString("isMgr"));
                request.getSession().setAttribute("LOGIN_USER",loginModel);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("/common/error");
            return false;
        }
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse res, Object obj, ModelAndView m) throws Exception {
        // TODO Auto-generated method stub
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object obj, Exception e) throws Exception {
        // TODO Auto-generated method stub
    }


}
